'use strict';

const jwt = require('jsonwebtoken');
const { Controller } = require('egg');
const { Op } = require('sequelize');

class StudentController extends Controller {
  //  用户列表
  async index() {
    const { query, service } = this.ctx;
    let { pageNum, pageSize, student_name, school_id, class_id } = query;
    const page = Number(pageNum) || 1;
    const size = Number(pageSize) || 10;
    const where = {
      student_name: { [Op.like]: `%${student_name}%`}
    };
    if (school_id) {
      where.school_id = school_id
    }
    if (class_id) {
      where.class_id = class_id
    }
    const users = await service.student.getPage(where, page, size);
    this.ctx.success(users);
  }

  // 所有列表
  async allList() {
    const { query, service } = this.ctx;
    let { ids } = query;
    let where = {};
    if (ids) {
      let idList = ids.split(',')
      where = {
        id: {
          [Op.in]: idList
        }
      }
    }
    const user = await service.student.allList(where);
    this.ctx.success(user);
  }

  // 删除用户
  async destroy() {
    const uid = Number(this.ctx.params.id);
    if (!uid) throw new Error('ID 有误');
    await this.ctx.service.student.deleteItemById(uid);
    this.ctx.success(uid); // 删除成功返回被删除的用户ID
  }

  // 修改用户信息
  async update() {
    const { ctx } = this;
    const id = ctx.params.id;
    const infos = ctx.request.body;
    if (!id) throw new Error('必须传递用户ID参数');
    if (Object.keys(infos).length === 0) throw new Error('请传递修改的内容');
    await ctx.service.student.updateItemById(id, infos);
    ctx.success(id, 200);
  }

  // 创建新用户
  async create() {
    const { ctx } = this;
    const data = ctx.request.body;
    const res = await ctx.service.student.createItem(data);
    ctx.success(res);
  }

  // 登录
  async login() {
    const { ctx } = this;
    const { request, service } = ctx;
    const data = request.body;
    const user = await service.student.loginByEmail(data);
    user.token = jwt.sign(user, this.config.keys);
    ctx.success(user);
  }
  // 激活
  async updateStatus() {
    const { ctx } = this;
    const { request, service } = ctx;
    const data = request.body;
    const user = await service.student.updateStatus(data);
    ctx.success(user);
  }
  // 修改密码
  async updatePassword() {
    const { ctx } = this;
    const { request, service } = ctx;
    const data = request.body;
    await service.student.updatePassword(ctx.student.id, data);
    ctx.success();
  }
}

module.exports = StudentController;
